package com.jp.knowledge.activity;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.fragment.VipZoneFragment;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.VipListModel;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.TabView;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/6/14.
 */
public class VipZoneActivity extends SlidingActivity {

    @ViewInject(R.id.drawerLayout)
    protected DrawerLayout drawerLayout;
    @ViewInject(R.id.tab_view)
    private TabView tabView;
    @ViewInject(R.id.sort_btn)
    protected ImageView sortBtn;
    @ViewInject(R.id.order_viewpager)
    private ViewPager viewPager;

    private List<String> tabNames;
    private List<VipListModel> vipListModels;
    private List<VipZoneFragment> fragments;

    private int type;
    private String cachePath;
    private FileCacheManager cacheManager;

    @Override
    protected int getResourceId() {
        return R.layout.activity_order;
    }

    @Override
    protected void init() {
        type = initType();
        tabNames = new ArrayList<>();
        vipListModels = new ArrayList<>();
        fragments = new ArrayList<>();
        viewPager.setBackgroundColor(mContext.getResources().getColor(R.color.white));
        viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }
            @Override
            public int getCount() {
                return fragments.size();
            }
            @Override
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }
        });
        tabView.setupWithViewPager(viewPager);
        cachePath = initCachePath();
        cacheManager = new FileCacheManager();

        sortBtn.setVisibility(View.GONE);
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        initTitleBar();
        initFragment();
        initTabLayout();
        readCache();
    }

    protected int initType(){
        return 0;
    }

    protected String initCachePath(){
        return mContext.getCacheDir() + "/vipZone_" + HttpHelper.uuid + "_" + type +  ".dat";
    }

    private void initTitleBar(){
        topName.setText("VIP会员区");
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        rightIcon.setVisibility(View.GONE);
        leftIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initFragment(){
        List<VipZoneFragment> tempFragment = new ArrayList<>();
        for(VipZoneFragment fragment : fragments) {
            for(VipListModel model : vipListModels){
                if(model.getPackageId() != null && model.getPackageId().equals(fragment.getPackageId())){
                    tempFragment.add(fragment);
                    break;
                }
            }
        }
        fragments.clear();

        for(int i = 0; i < vipListModels.size(); i++){
            String packageId = vipListModels.get(i).getPackageId();
            for(VipZoneFragment fragment : tempFragment)
                if(fragment.getPackageId().equals(packageId)){
                    fragments.add(fragment);
                    tempFragment.remove(fragment);
                    break;
                }
            if(fragments.size() == i)
                fragments.add(VipZoneFragment.newInstance(null, packageId));
        }
        viewPager.getAdapter().notifyDataSetChanged();
    }

    private void initTabLayout(){
        tabNames.clear();
        for(int i = 0; i < vipListModels.size(); i++) {
            String tabName = vipListModels.get(i).getGradeName();
            if(tabName == null)
                tabName = "";
            tabNames.add(tabName);
        }
        if(tabNames.size() <= 1)
            tabView.setVisibility(View.GONE);
        else
            tabView.setVisibility(View.VISIBLE);
        if(tabNames.size() == 1)
            topName.setText(tabNames.get(0) + "区");
        tabView.setTabItems(tabNames);
    }

    private void readCache(){
        Observable.create(new Observable.OnSubscribe<List<VipListModel>>() {
            @Override
            public void call(Subscriber<? super List<VipListModel>> subscriber) {
                List<VipListModel> data = (List<VipListModel>) cacheManager.readObject(cachePath);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<VipListModel>>() {
            @Override
            public void onCompleted() {
                getTabData();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<VipListModel> data) {
                if(data != null) {
                    vipListModels = data;
                    initFragment();
                    initTabLayout();
                }
                onCompleted();
            }
        });
    }

    private void getTabData(){
        JsonObject param = new JsonObject();
        param.addProperty("type", type);
        HttpHelper.getInstance(mContext).vipList(param, 0x01, new ResultSubscriber.OnResultListener() {
            @Override
            public void onStart(int requestType) {
//                loading.show();
            }
            @Override
            public void onCompleted(int requestType) {
                loading.cancel();
            }
            @Override
            public void onError(int requestType) {
                onCompleted(requestType);
            }
            @Override
            public void onNext(IModel data, int requestType) {
                if(data.getErrcode() != 0){
                    ToasUtil.toast(mContext, data.getMessage());
                } else{
                    vipListModels.clear();
                    List<VipListModel> vipListModelList = data.getList(VipListModel.class);
                    if(vipListModelList != null && vipListModelList.size() > 0)
                        vipListModels.addAll(vipListModelList);
                    initFragment();
                    initTabLayout();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            cacheManager.wirteObject(vipListModels, cachePath);
                        }
                    }).start();
                }
            }
        });
    }
}
